﻿using apiframworkTest.boot;
using apiframworkTest.Common;
using apiframworkTest.Extend;
using Autofac;
using Autofac.Integration.WebApi;
using Ef.Repository;
using MongoDbRepository;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Runtime.Remoting.Contexts;
using System.Web;
using System.Web.Http;
using System.Web.Routing;
using System.Web.SessionState;

namespace apiframworkTest
{
    public class WebApiApplication : System.Web.HttpApplication
    {


        //初始化开启session 
        public override void Init()
        {
            this.PostAuthenticateRequest += (sender, e) => HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);

            this.BeginRequest += WebApiApplication_BeginRequest;
            base.Init();
        }

        private void WebApiApplication_BeginRequest(object sender, EventArgs e)
        {
            if (Request.Headers.AllKeys.Contains("Origin") && Request.HttpMethod == "OPTIONS")
            {
                Response.Flush();
            }
        }

        protected void Application_Start()
        {
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
            GlobalConfiguration.Configure(WebApiConfig.Register);
            MongoDBBootstrapper.Bootstrap();
            AutoFacBootStrapper.Configure();
            //注册全局异常处理
            GlobalConfiguration.Configuration.Filters.Add(new MyuExceptionFilterAttribute());
          
            //注册全局的权限验证
            GlobalConfiguration.Configuration.Filters.Add(new MyuAuthAttribute());

           


            //var builder = new ContainerBuilder();
            //builder.RegisterApiControllers(Assembly.GetExecutingAssembly());
            ////builder.RegisterType<DbService>();
            //var container = builder.Build();
            //var resolver = new AutofacWebApiDependencyResolver(container);
            //GlobalConfiguration.Configuration.DependencyResolver = resolver;

        }


        protected void Application_Error(object sender, EventArgs e)
        {
            Exception exception = Server.GetLastError();
            Response.Clear();
        }
      
    }
}
